package com.ittest.service.impl;

import com.alicp.jetcache.anno.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ittest.dao.BookDao;
import com.ittest.domain.Book;
import com.ittest.service.IBookservice;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class IBookServiceImpl extends ServiceImpl<BookDao, Book> implements IBookservice {

    @Autowired
    private BookDao bookDao;



    @Override
    @Cached(name = "book_",key = "#id",expire = 3600,cacheType = CacheType.REMOTE)
    //@CacheRefresh(refresh = 5) //为防止不同系统修改数据后没有同步，加上该注解，按照一定时间取查询更新数据，按照时间取刷新数据
    public Book getById(Integer id) {
            return bookDao.selectById(id);
    }

    @Override
    public boolean save(Book book) {
        return bookDao.insert(book) > 0;
    }



    @Override
    @CacheUpdate(name = "book_",key = "#book.id",value = "#book")//加上之后这里在更新完数据库中的数据之后会同步更新内存中的数据（也就是redis中的数据）
    public Boolean update(Book book) {
        return bookDao.updateById(book) > 0;
    }


    @Override
    @CacheInvalidate(name = "book_",key = "#id") //加上之后会同步删除内存中的数据（redis中的）
    public Boolean delete(Integer id){
        return bookDao.deleteById(id) > 0;
    }

    @Override
    public List<Book> getAll() {
        return bookDao.selectList(null);
    }


    @Override
    public IPage<Book> getPage(int currentPasge, int pageSize) {
        IPage page = new Page(currentPasge,pageSize);
        bookDao.selectPage(page, null);

        return page;
    }



    //加上条件查询的分页查询

    @Override
    public IPage<Book> getPage(int currentPasge, int pageSize, Book book) {
        LambdaQueryWrapper<Book> lqw = new LambdaQueryWrapper<>();
        lqw.like(Strings.isNotEmpty(book.getType()),Book::getType,book.getType());
        lqw.like(Strings.isNotEmpty(book.getName()),Book::getName,book.getName());
        lqw.like(Strings.isNotEmpty(book.getDescription()),Book::getDescription,book.getDescription());
        IPage page = new Page(currentPasge,pageSize);
        bookDao.selectPage(page,lqw);

        return page;
    }

}
